package com.ptl.bp.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ptl.bp.config.ApiResult;
import com.ptl.bp.config.PermissionRequire;
import com.ptl.bp.config.GlobalUserContext;
import com.ptl.bp.entity.UserEntity;
import com.ptl.bp.dto.UserQuery;
import com.ptl.bp.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

import static com.ptl.bp.config.enums.UserRole.ADMIN;

@Slf4j
@Tag(name = "用户管理")
@RestController
@RequestMapping("/api/user")
public class UserController {

    @Resource
    private UserService userService;

    @Operation(summary = "创建用户")
    @PostMapping
    @PermissionRequire(ADMIN)
    public ApiResult<Boolean> create(@RequestBody UserEntity user) {
        return ApiResult.success(userService.createUser(user));
    }

    @Operation(summary = "更新用户信息")
    @PutMapping
    public ApiResult<Boolean> update(@RequestBody UserEntity user) {
        if (userService.isExists(user)) {
            throw new RuntimeException("用户名已存在");
        }
        return ApiResult.success(userService.updateById(user));
    }

    @Operation(summary = "删除用户")
    @DeleteMapping("/{id}")
    public ApiResult<Boolean> delete(@PathVariable Long id) {
        return ApiResult.success(userService.removeById(id));
    }

    @Operation(summary = "批量删除用户")
    @DeleteMapping("/batch")
    @PermissionRequire(ADMIN)
    public ApiResult<Boolean> batchDelete(@RequestBody List<Long> ids) {
        return ApiResult.success(userService.removeByIds(ids));
    }

    @Operation(summary = "获取用户详情")
    @GetMapping("/{id}")
    public ApiResult<UserEntity> getById(@PathVariable Long id) {
        return ApiResult.success(userService.getById(id));
    }

    @Operation(summary = "获取用户详情")
    @GetMapping("/getCurrentUser")
    public ApiResult<UserEntity> getCurrentUser() {
        Long id = GlobalUserContext.getUser().getUserId();
        return ApiResult.success(userService.getById(id));
    }

    @Operation(summary = "分页查询用户")
    @GetMapping("/page")
    public ApiResult<IPage<UserEntity>> page(
            @Parameter(description = "分页参数") Page<UserEntity> page,
            @Parameter(description = "查询条件") UserQuery query) {
        page = userService.lambdaQuery()
                .like(StringUtils.isNotBlank(query.getUsername()), UserEntity::getUsername, query.getUsername())
                .eq(query.getRole() != null, UserEntity::getRole, query.getRole())
                .orderByDesc(UserEntity::getId)
                .page(page);
        return ApiResult.success(page);
    }
}
